﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WPF_DbCenter.CommonMethod;
using System.Diagnostics;
using System.Data.Common;
using System.Data;
using WPF_DbCenter.AdditionUI;
using System.Collections.ObjectModel;
using WPF_DbCenter.BaseUI;
using XLCS.Common;
using CustomControl.NewXLAGControl;
using System.Data.SqlServerCe;
using wf=System.Windows.Forms;
using System.IO;
using WPF_DbCenter.SqlCE.UI;
using WPF_DbCenter.SqlCE.AdditionUI;
using System.ServiceProcess;

namespace WPF_DbCenter.UI
{
    /// <summary>
    /// Interaction logic for Main.xaml
    /// </summary>

    public partial class Main : System.Windows.Window, IWindowIDE
    {

        public IDbEnginer X_MainEnginer
        {
            get
            {
                return App.MainEngineer;
            }
        }
        ObservableCollection<String> CmdHistoryList = new ObservableCollection<String>();
        private int CommandCurrency = 0;

        public Main()
        {
            
            Xceed.Wpf.Controls.Licenser.LicenseKey = Properties.Settings.Default.MyXceedGridLisencer;
            Xceed.Wpf.DataGrid.Licenser.LicenseKey = Properties.Settings.Default.MyXceedGridLisencer;
            InitializeComponent();

            Loaded += new RoutedEventHandler(Main_Loaded);
            Unloaded += new RoutedEventHandler(Main_Unloaded);
            mainTreeView.SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(treeMainTable_SelectedItemChanged);
            txtMainCmd.KeyDown += new KeyEventHandler(txtMainCmd_KeyDown);

            System.Windows.Forms.DataGridViewCellStyle style = new System.Windows.Forms.DataGridViewCellStyle();
            {
                style.BackColor = System.Drawing.Color.Beige;
                style.ForeColor = System.Drawing.Color.Brown;
                style.Font = new System.Drawing.Font("Verdana", 8);

            }
            
            this.mainTreeView.ContextMenuOpening += new ContextMenuEventHandler(treeMainTable_ContextMenuOpening);
            treeMainTable_ContextMenuOpening(null, null);
            txtMainCmd.SpellCheck.IsEnabled = true;
            progressBar1.Visibility = Visibility.Hidden;
            //dataGridView1.Columns[0].Width = ClientRectangle.Width / dataGridView1.ColumnCount;
            //dataGridView1.Columns[1].Width = ClientRectangle.Width / dataGridView1.ColumnCount;

            // Apply the style as the default cell style.
            //dataGridView1.AlternatingRowsDefaultCellStyle = style;

            CmdHistoryList.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(CmdHistoryList_CollectionChanged);

        }

        void CmdHistoryList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            CommandCurrency = CmdHistoryList.Count;
        }

        /// <summary>
        /// Command Text Key event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void txtMainCmd_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if ((e.Key == Key.B) && (Keyboard.Modifiers==ModifierKeys.Control))
            {
                BackCmd(null, null);
            }
            else if ((e.Key == Key.N) && (Keyboard.Modifiers==ModifierKeys.Control))
            {
                NextCmd(null, null);
            }

            if (String.IsNullOrEmpty(txtMainCmd.Text))
            {
                return;
            }

            if (e.Key == Key.Enter)
            {
                butQueryClick(null, null);
            }
             
            else if ((e.Key == Key.J) && (Keyboard.Modifiers==ModifierKeys.Control))
            {
                DynaControls.GetDbTypeControl dj = new WPF_DbCenter.DynaControls.GetDbTypeControl();
                dj.Location = new System.Drawing.Point(200, 200);
                dj.AfterSelectedValue += new WPF_DbCenter.DynaControls.GetDbTypeControl.Del_AfterSelectedValue(AcceptValue);

                dj.ShowDialog();

                e.Handled = true;
            }

            
        }

        void AcceptValue(string result)
        {
            if (String.IsNullOrEmpty(txtMainCmd.SelectedText))
            {
                txtMainCmd.Text += "  "+result;
            }
            else
            {
                txtMainCmd.SelectedText = string.Empty;

                int start=txtMainCmd.SelectionStart;
                string prefix=txtMainCmd.Text.Substring(0,start);
                string appdenfix = txtMainCmd.Text.Substring(start,txtMainCmd.Text.Length-start);

                prefix += result;

                txtMainCmd.Text = prefix + appdenfix;
            }
            
            //this.Activate();
            //this.txtMainCmd.Focus();
        }


        void treeMainTable_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {

        }

        

        /// <summary>
        /// Display the column info of this table in the curretn TreeViewItem
        /// </summary>
        /// <param name="selectedItem"></param>
        /// <param name="p"></param>
        private void ListColumnsInTable(TreeViewItem selectedItem, string tableName)
        {
     

            TreeViewItem columnItem = new TreeViewItem();
            columnItem.Header = "Columns";
            columnItem.Tag = new TreeItemArgs(){ItemType=TreeItemType.ColumnParentNode,TableName=tableName};

            selectedItem.Items.Add(columnItem);

            TreeViewItem indexItem = new TreeViewItem();

            indexItem.Header = "Indexes";
            indexItem.Tag = new TreeItemArgs(){ItemType=TreeItemType.IndexParentNode, TableName=tableName};
            selectedItem.Items.Add(indexItem);

            DataSet dataRowCollections =App.MainEngineer.GetColumnInfoFromTable(tableName);
            foreach (DataRow row in dataRowCollections.Tables[0].Rows)
            {
                TreeViewItem item = new TreeViewItem();
                item.Header = String.Format("{0}  {1}  {2}", row["COLUMN_NAME"], row["DATA_TYPE"], row["CHARACTER_MAXIMUM_LENGTH"]);
                item.Tag = new TreeItemArgs() { ItemType = TreeItemType.Column, TableName = tableName, ColumnName = row["COLUMN_NAME"].ToString() };
                columnItem.Items.Add(item);
            }

            DataSet indexCollections = App.MainEngineer.GetIndexInfoFromTable(tableName);

            foreach (DataRow row in indexCollections.Tables[0].Rows)
            {
                TreeViewItem item = new TreeViewItem();
                item.Header = String.Format("{0}  {1}  {2}", row["INDEX_NAME"],"","");
                item.Tag = new TreeItemArgs(){ItemType=TreeItemType.Index, TableName=tableName, IndexName=row["INDEX_NAME"].ToString()};
                indexItem.Items.Add(item);
            }


        }

        void Main_Loaded(object sender, RoutedEventArgs e)
        {
            //Clear to Orginal Status
            this.mainTreeView.Items.Clear();

            foreach (string table in App.MainEngineer.TableList)
            {
                TreeViewItem item = new TreeViewItem();
                item.Header = table;
                item.Tag = new TreeItemArgs() { ItemType = TreeItemType.Table,TableName= table };

                mainTreeView.Items.Add(item);
            }
            
            foreach (TreeViewItem selectedItem in mainTreeView.Items)
            {
                if (selectedItem != null)
                {
                    TreeItemArgs args = selectedItem.Tag as TreeItemArgs;
                    if (args != null)
                    {
                        if (args.ItemType == TreeItemType.Table)
                        {
                            ListColumnsInTable(selectedItem, args.TableName);
                        }
                    }
                }
        
            }


            Utility.TreeViewHelper.ExpandAll(mainTreeView);
        }

        void Main_Unloaded(object sender, RoutedEventArgs e)
        {
            //try
            //{
            //    ((SqlCeDatabase)App.MainEngineer.DbHandler).CloseSharedConnection();
            //    ResetUI();
            //    Close();
            //    Window top = this.Tag as Window;

            //    Debug.Assert(top != null);
            //    top.Show();
            //}
            //catch(Exception ee)
            //{
            //    ProcessException.DisplayErrors(ee);
            //}
        }

        private void ResetUI()
        {
            mainTreeView.Items.Clear();
            txtMainCmd.Text = String.Empty;
        }

        private void exitMenu_Checked(object sender, RoutedEventArgs e)
        {
            Main_Unloaded(null, null);
        }

        private void ClearCmd(object sender, RoutedEventArgs e)
        {
            txtMainCmd.Text = string.Empty;
        }

        private void menuAbout_Click(object sender, RoutedEventArgs e)
        {
            About about = new About();
            about.Owner = this;
            
            about.ShowDialog();
        }

        /// <summary>
        /// Sync
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Sync_Click(object sender, RoutedEventArgs e)
        {
            DataExchange de = new DataExchange();
            de.Owner = this;
            de.ShowDialog();
        }

        private void help_Click(object sender, RoutedEventArgs e)
        {
            Help help = new Help();
            help.Owner = this;
            help.ShowDialog();
        }

        private void option_Click(object sender, RoutedEventArgs e)
        {
            Options op = new Options();
            op.Owner = this;
            op.ShowDialog();
        }

        private void BackCmd(object sender, RoutedEventArgs e)
        {
            if (CommandCurrency - 1 >= 0)
            {
                CommandCurrency--;
                txtMainCmd.Text = CmdHistoryList[CommandCurrency];
            }
        }

        private void NextCmd(object sender, RoutedEventArgs e)
        {
            if (CommandCurrency + 1 < CmdHistoryList.Count)
            {
                CommandCurrency++;
                txtMainCmd.Text = CmdHistoryList[CommandCurrency];
            }
        }

        #region IWindowIDE Members

        public Window MyHost
        {
            get
            {
                return this;

            }
        }

        #endregion

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            Utility.TreeViewHelper.DisExpandAll(mainTreeView);
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Utility.TreeViewHelper.ExpandAll(mainTreeView);
        }
        /// <summary>
        /// Generate business entity
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void generateBusinessEntity_Click(object sender, RoutedEventArgs e)
        {
            GenerateBusinessEntity gf=new GenerateBusinessEntity();

           gf.ShowDialog();
        }

        private void OnSyncClick(object sender, RoutedEventArgs e)
        {

        }

        private void exit_Click(object sender, RoutedEventArgs e)
        {
            App.Current.Shutdown();
        }

        /// <summary>
        /// Open Sql Command From File
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenScirpt_Click(object sender, RoutedEventArgs e)
        {
            using (wf.OpenFileDialog of = new System.Windows.Forms.OpenFileDialog())
            {
                of.Filter = "Sql Script(*.sql)|*.sql|Text File(*.txt)|*.txt|All Files(*.*)|*.*";
                if (of.ShowDialog() == wf.DialogResult.OK)
                {
                    try
                    {
                        string sqlConntent=File.ReadAllText(of.FileName);
                        txtMainCmd.Text = sqlConntent;
                    }
                    catch (Exception ee)
                    {
                        XLCS.Common.ProcessException.DisplayErrors(ee);
                    }
                }
            }
        }

        /// <summary>
        /// Save Sql Script to File
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveScirpt_Click(object sender, RoutedEventArgs e)
        {
            using (wf.SaveFileDialog of = new System.Windows.Forms.SaveFileDialog())
            {
                of.Filter = "Sql Script(*.sql)|*.sql|Text File(*.txt)|*.txt|All Files(*.*)|*.*";
                if (of.ShowDialog() == wf.DialogResult.OK)
                {
                    try
                    {
                        string sqlConntent = txtMainCmd.Text;
                        FileStream fs=File.Create(of.FileName);
                        fs.Flush();
                        fs.Close();
                        fs.Dispose();

                        using (StreamWriter w = File.AppendText(of.FileName))
                        {
                            w.Write(txtMainCmd.Text);
                            w.Flush();
                            w.Close();
                        }

                    }
                    catch (Exception ee)
                    {
                        XLCS.Common.ProcessException.DisplayErrors(ee);
                    }
                }
            }
        }

        /// <summary>
        /// Generate Linq Context Mapping
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GLinq_Click(object sender, RoutedEventArgs e)
        {
            GenerateLinqContext gl = new GenerateLinqContext();
            gl.Show();
        }


        private void syncSqlServer_CLick(object sender, RoutedEventArgs e)
        {
            SqlServer2Sdf ssf = new SqlServer2Sdf();
            ssf.Owner = this;
            ssf.Show();
        }

        private void syncAccess_Click(object sender, RoutedEventArgs e)
        {
            Access2SDF sf = new Access2SDF();
            sf.Owner = this;
            sf.Show();

        }

        private void syncExcel_Click(object sender, RoutedEventArgs e)
        {
            Excel2SDF sf = new Excel2SDF();
            sf.Owner = this;
            sf.Show();
        }

        private void syncCSV_Click(object sender, RoutedEventArgs e)
        {
            Csv2Sdf sf = new Csv2Sdf();
            sf.Owner = this;
            sf.Show();
        }

        private void syncMySql_Click(object sender, RoutedEventArgs e)
        {
            CommonUtil.ResultArgs args = CommonUtil.DetectMySqlService();
            if (!args.HasThisService)
            {
                MessageBox.Show("You do not has mysql database installed ,or not running the service");
                return;
            }
            if (args.status != ServiceControllerStatus.Running)
            {
                if (!CommonUtil.StartServices(CommonUtil.MySqlServiceName))
                {
                    MessageBox.Show("Your mysql database can't run .Process will cancel");
                    return;
                }
            }

            AdditionUI.MySql2SDF msdf = new WPF_DbCenter.AdditionUI.MySql2SDF();
            msdf.Owner = this;
            msdf.ShowDialog();
        }

        /// <summary>
        /// Sync data from sqlce
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void but_SyncFromSqlCE_Click(object sender, RoutedEventArgs e)
        {
            Sdf2Sdf s = new Sdf2Sdf();
            s.Show();
        }

        /// <summary>
        /// Clear all data in all tables of sqlce db files
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void butResetDataInSqlceDb_Click(object sender, RoutedEventArgs e)
        {
            ResetData r = new ResetData();
            r.Show();
        }

        private void close_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Download online sqlce database file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void butDownload_Click(object sender, RoutedEventArgs e)
        {
            DownloadSdf ds = new DownloadSdf();
            ds.Show();
        }


    }
}